import time
from datetime import datetime
import requests
# from pypushdeer import PushDeer
from BarkNotificator import BarkNotificator
# import json
import os
import json
import pytz
import schedule


def format_time(timestamp):
    tz = pytz.timezone("Asia/Shanghai")
    return datetime.fromtimestamp(timestamp, tz).strftime("%Y-%m-%d  %H:%M:%S")

class PostPusher:
    # 类属性
    create_time = ""
    leader_json = {}  # name:last_post_id

    # {leader:[url,headers,body]}
    leader_post = {
        'HoangthaiCrypto1994': ["https://www.binance.com/bapi/futures/v1/friendly/future/copy-trade/lead-portfolio/position-history", {
            'accept': '*/*',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'bnc-level': '0',
            'bnc-location': 'CN',
            'bnc-time-zone': 'Asia/Shanghai',
            'bnc-uuid': '36f643ec-51c4-4461-8b3c-e057aa78af7b',
            'clienttype': 'web',
            'content-type': 'application/json',
            'csrftoken': 'd41d8cd98f00b204e9800998ecf8427e',
            'device-info': 'eyJzY3JlZW5fcmVzb2x1dGlvbiI6IjE5MjAsMTIwMCIsImF2YWlsYWJsZV9zY3JlZW5fcmVzb2x1dGlvbiI6IjE4NzAsMTE3NSIsInN5c3RlbV92ZXJzaW9uIjoiTWFjIE9TIDEwLjE1LjciLCJicmFuZF9tb2RlbCI6InVua25vd24iLCJzeXN0ZW1fbGFuZyI6InpoLUNOIiwidGltZXpvbmUiOiJHTVQrMDg6MDAiLCJ0aW1lem9uZU9mZnNldCI6LTQ4MCwidXNlcl9hZ2VudCI6Ik1vemlsbGEvNS4wIChNYWNpbnRvc2g7IEludGVsIE1hYyBPUyBYIDEwXzE1XzcpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS8xMzUuMC4wLjAgU2FmYXJpLzUzNy4zNiIsImxpc3RfcGx1Z2luIjoiUERGIFZpZXdlcixDaHJvbWUgUERGIFZpZXdlcixDaHJvbWl1bSBQREYgVmlld2VyLE1pY3Jvc29mdCBFZGdlIFBERiBWaWV3ZXIsV2ViS2l0IGJ1aWx0LWluIFBERiIsImNhbnZhc19jb2RlIjoiZGRmOGRjNDUiLCJ3ZWJnbF92ZW5kb3IiOiJHb29nbGUgSW5jLiAoQXBwbGUpIiwid2ViZ2xfcmVuZGVyZXIiOiJBTkdMRSAoQXBwbGUsIEFOR0xFIE1ldGFsIFJlbmRlcmVyOiBBcHBsZSBNNCwgVW5zcGVjaWZpZWQgVmVyc2lvbikiLCJhdWRpbyI6IjEyNC4wNDM0NjYwNzExNDcxMiIsInBsYXRmb3JtIjoiTWFjSW50ZWwiLCJ3ZWJfdGltZXpvbmUiOiJBc2lhL1NoYW5naGFpIiwiZGV2aWNlX25hbWUiOiJDaHJvbWUgVjEzNS4wLjAuMCAoTWFjIE9TKSIsImZpbmdlcnByaW50IjoiNDYxYjVjYWNjNDNlNzg0MjViNzgyM2ZkMjQ5NjhkZjIiLCJkZXZpY2VfaWQiOiIiLCJyZWxhdGVkX2RldmljZV9pZHMiOiIifQ==',
            'dnt': '1',
            'fvideo-id': '33f68509f3f0af94b471ffc03ac67b244820ca84',
            'fvideo-token': 'j81mYDRTKM5pOSGMOoSFy1qYnHP4HnykMQa2QB8LTaHPFqNPJkZUJ4RPpdvmpqtxDSuGrFpupZ7FrVIi/k3VMRyhf18fKw0otb0H3L400c2HhOsfZ8JWkjTStI+gQ9GxptoC1bzGtYsEFCK+BHnMy09hjLgcN/SG1QGAM/kt0RoT/jqQ23MESFDZ1PV1BXC6I=26',
            'lang': 'zh-CN',
            'origin': 'https://www.binance.com',
            'priority': 'u=1, i',
            'referer': 'https://www.binance.com/zh-CN/copy-trading/lead-details/4284698970319737345?timeRange=7D',
            'sec-ch-ua': '"Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
            'x-passthrough-token': '',
            'x-trace-id': '789dcc89-897e-48a4-a8da-6472e890f75b',
            'x-ui-request-trace': '789dcc89-897e-48a4-a8da-6472e890f75b'
        }, {
            "pageNumber": 1,
            "pageSize": 10,
            "portfolioId": "4284698970319737345",
            "sort": "OPENING"
        }],
        "index_指南针": ["https://www.binance.com/bapi/futures/v1/friendly/future/copy-trade/lead-portfolio/position-history", {
            'accept': '*/*',
            'accept-language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'bnc-level': '0',
            'bnc-location': 'CN',
            'bnc-time-zone': 'Asia/Shanghai',
            'bnc-uuid': '36f643ec-51c4-4461-8b3c-e057aa78af7b',
            'clienttype': 'web',
            'content-type': 'application/json',
            'csrftoken': 'd41d8cd98f00b204e9800998ecf8427e',
            'device-info': 'eyJzY3JlZW5fcmVzb2x1dGlvbiI6IjE5MjAsMTIwMCIsImF2YWlsYWJsZV9zY3JlZW5fcmVzb2x1dGlvbiI6IjE4NjksMTE3NSIsInN5c3RlbV92ZXJzaW9uIjoiTWFjIE9TIDEwLjE1LjciLCJicmFuZF9tb2RlbCI6InVua25vd24iLCJzeXN0ZW1fbGFuZyI6InpoLUNOIiwidGltZXpvbmUiOiJHTVQrMDg6MDAiLCJ0aW1lem9uZU9mZnNldCI6LTQ4MCwidXNlcl9hZ2VudCI6Ik1vemlsbGEvNS4wIChNYWNpbnRvc2g7IEludGVsIE1hYyBPUyBYIDEwXzE1XzcpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS8xMzQuMC4wLjAgU2FmYXJpLzUzNy4zNiIsImxpc3RfcGx1Z2luIjoiUERGIFZpZXdlcixDaHJvbWUgUERGIFZpZXdlcixDaHJvbWl1bSBQREYgVmlld2VyLE1pY3Jvc29mdCBFZGdlIFBERiBWaWV3ZXIsV2ViS2l0IGJ1aWx0LWluIFBERiIsImNhbnZhc19jb2RlIjoiZGRmOGRjNDUiLCJ3ZWJnbF92ZW5kb3IiOiJHb29nbGUgSW5jLiAoQXBwbGUpIiwid2ViZ2xfcmVuZGVyZXIiOiJBTkdMRSAoQXBwbGUsIEFOR0xFIE1ldGFsIFJlbmRlcmVyOiBBcHBsZSBNNCwgVW5zcGVjaWZpZWQgVmVyc2lvbikiLCJhdWRpbyI6IjEyNC4wNDM0NjYwNzExNDcxMiIsInBsYXRmb3JtIjoiTWFjSW50ZWwiLCJ3ZWJfdGltZXpvbmUiOiJBc2lhL1NoYW5naGFpIiwiZGV2aWNlX25hbWUiOiJDaHJvbWUgVjEzNC4wLjAuMCAoTWFjIE9TKSIsImZpbmdlcnByaW50IjoiNTMyNzg0ZjIwOTRhNGFhNjA1MTBmOWY1N2I1MGY5MGMiLCJkZXZpY2VfaWQiOiIiLCJyZWxhdGVkX2RldmljZV9pZHMiOiIifQ==',
            'dnt': '1',
            'fvideo-id': '33f68509f3f0af94b471ffc03ac67b244820ca84',
            'fvideo-token': 'bJfuuK8s2pBPy7CDzPtxRuSsmIWFB0u7KoYfrvHT3x4k2e+f9cmEdYypMvMill57dAhz+JJzKe+hH+uyQUWxe1rloEWinsrEH3m9BDMnArLpUFKPZ2NDQkvwsvfqEt9JGbvTlsN+X42GWliuJ+In4sHXIrGCHcKRm0w42OK2b/pDr3hIWZyLa6f5XSfZWIPcY=04',
            'lang': 'zh-CN',
            'origin': 'https://www.binance.com',
            'priority': 'u=1, i',
            'referer': 'https://www.binance.com/zh-CN/copy-trading/lead-details/4191203708922689281?timeRange=7D',
            'sec-ch-ua': '"Chromium";v="134", "Not:A-Brand";v="24", "Google Chrome";v="134"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36',
            'x-passthrough-token': '',
            'x-trace-id': 'c318f5ac-aa22-42ed-bb88-e3d174522abb',
            'x-ui-request-trace': 'c318f5ac-aa22-42ed-bb88-e3d174522abb'
        }, {
            "pageNumber": 1,
            "pageSize": 10,
            "portfolioId": "4191203708922689281",
            "sort": "OPENING"
        }
        ]}

    # 构造方法，用于初始化对象的属性

    def __init__(self,key):
        # 实例属性
        self.key = key
        # self.file_path = file_path

        for k in self.leader_post:
            self.leader_json[k] = {}
        
        self.read_leader_json()

    def read_leader_json(self):
        for key,item in self.leader_post.items():
            file_path = f"{os.getcwd()}/{key}.json"
            try:
                # 以只读模式打开文件
                with open(file_path, "r", encoding="utf-8") as file:
                    content = file.read()
                    print(f"从文件 {file_path} 中读取到内容")
                    self.leader_json[key] = json.loads(content)
            except FileNotFoundError:
                print(f"文件 {file_path} 未找到。")
            except Exception as e:
                print(f"读取文件时出现错误: {e}")

    def write_leader_json(self,key):
        file_path = f"{os.getcwd()}/{key}.json"
        try:
            # 以写入模式打开文件，如果文件不存在则创建
            with open(file_path, "w", encoding="utf-8") as file:
                file.write(json.dumps(self.leader_json[key], ensure_ascii=False))
            print(f"成功写入文件 {file_path}")
        except Exception as e:
            print(f"写入文件时出现错误: {e}")

    def push(self, title, content):
        # url = f"https://api2.pushdeer.com/message/push?pushkey={self.key}&text={content}"
        # url = f"https://api2.pushdeer.com/message/push?pushkey={self.key}&text=发布时间:{self.create_time}&desp={content}&type=markdown"
        # requests.get(url, timeout=10)

        # pushdeer = PushDeer(pushkey=self.key)
        # pushdeer.send_markdown(
        #     f"发布时间:{self.create_time}", desp=content
        # )

        bark = BarkNotificator(device_token=self.key)
        bark.send(title=f"{title}", content=content,ringtone='minuet.caf', call='1')

        # url = "https://api.day.app/push"
        # payload = {
        #     "title": f"发布时间:{self.create_time}",
        #     "body": content,
        #     "device_key": self.key,
        # }
        # headers = {"Content-Type": "application/json; charset=utf-8"}
        # json_data = json.dumps(payload)
        # requests.post(url=url,data=json_data,headers=headers,timeout=10)

    def query_leader_position_history(self, leader, url, header,body):
        payload = json.dumps(body)
        headers = header

        status_code = 0
        rsp_text = ""
        try:
            response = requests.post(
                url, headers=headers, data=payload, timeout=10)
            status_code = response.status_code
            rsp_text = response.text
        except requests.exceptions.ConnectionError as e:
            print(f"Error connecting to the server: {e}")
        except requests.exceptions.HTTPError as e:
            print(f"HTTP error occurred: {e}")
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
        except Exception as e:
            print(f"other err: {e}")

        # 检查响应状态码
        if status_code != 200:
            print(f"请求失败，状态码: {status_code}")
            # 打印响应内容
            print(rsp_text)
            self.query_leader_position_history(leader, url, header,body)
            time.sleep(1)
            return

        try:
            # 将响应内容解析为 Python 对象
            json_data = response.json()
            # print("解析后的 Python 对象类型:", type(json_data))
            # print("解析后的数据:", json_data)
        except ValueError:
            print("响应内容不是有效的 JSON 格式。")

        previous_statuses = {}
        leader_json = self.leader_json[leader]
        if leader_json:
            previous_statuses = {item['id']: {key: value for key, value in item.items()} for item in leader_json['data']['list']}
        
        current_statuses = {item['id']: {key: value for key, value in item.items()} for item in json_data['data']['list']}
        notice =  ""

        # 检查list的新增项
        new_items = set(current_statuses.keys()) - set(previous_statuses.keys())
        if new_items:
            for new_id in new_items:
                previous_statuses[new_id] = current_statuses[new_id]
                symbol=current_statuses[new_id]['symbol']
                side=current_statuses[new_id]['side']
                avgCost=current_statuses[new_id]['avgCost']
                updateTime = format_time(current_statuses[new_id]['updateTime'] / 1000)
                
                notice += f"{updateTime}\n\nNew {symbol} {side} {avgCost}\n\n-------\n\n"

        if previous_statuses is not None:
            # 检查status的变化
            for item_id, item in current_statuses.items():
                status = item['status']
                if previous_statuses[item_id]['status'] != status:
                    symbol = item['symbol']
                    avg_close_price = item['avgClosePrice']
                    notice += f"{symbol} changed to {status} {avg_close_price}\n\n-------\n\n"

        if notice:
            self.leader_json[leader] = json_data
            self.write_leader_json(leader)
            title = f"{leader}"
            content = notice
            # for item in image_list:
            #     content+=f"![]({item})"
            self.push(title, content)
        
        # idx = 2
        # post_id = str(json_data["data"]["contents"][idx]["id"])
        # shareLink = json_data["data"]["contents"][idx]["shareLink"]
        # text = json_data["data"]["contents"][idx]["bodyTextOnly"]
        # # image_list = json_data["data"]["contents"][idx]["imageList"]
        # # 给定的毫秒级时间戳
        # timestamp_ms = json_data["data"]["contents"][idx]["createTime"]
        # # 将毫秒转换为秒
        # timestamp_s = timestamp_ms / 1000

        # create_time = format_time(timestamp_s)

        # print("解析后的数据:", post_id)
        # if (post_id != self.leader_json[leader]):
        #     self.leader_json[leader] = post_id
        #     self.write_leader_json(leader)

        #     title = f"{leader} {create_time}"
        #     content = f"{shareLink}\n\n{text}"
        #     # for item in image_list:
        #     #     content+=f"![]({item})"
        #     self.push(title, content)


if __name__ == "__main__":
    # PushDeer
    # key = "PDU33885Tx7RPpCiio0MyRF0ySjZz2GVdGWF9rkWf"
    # bark
    # key = "2KzwDuZCgNSSqjqf6pRcZU"
    key = "5e926333c83d7bb5c9e65e2550ed9684e7d1357daa0f8d7cf865b57439c0aed0"
   
    post_pusher = PostPusher(key)

    def job():
        for k,item in post_pusher.leader_post.items():
            # if k != '加密菲姐':
            #   continue
            post_pusher.query_leader_position_history(k, item[0], item[1],item[2])

    job()

    schedule.every(30).seconds.do(job)
    while True:
        schedule.run_pending()
        time.sleep(1)
